<?php
/**
 * Created by PhpStorm.
 * Author: DaXiong
 * Date: 2018/10/29
 * Time: 14:22
 */

namespace App\Http\Controllers\Admin;


use App\Http\Controllers\Controller;
use App\User;
use Illuminate\Support\Facades\Log;

class UserController extends Controller
{
    /**
     * 获取 微信用户列表信息
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function index(){

        $params = [
            'id' => (int)request('id',''),
            'nickname' => (string)request('username',''),
            'role_id' => (string)request('role_id',''),
        ];
        $info = User:: where(function ($query)use($params) {
            if ($params['id']){
                $query->where('id',$params['id']);
            }
            if ($params['role_id']){
                $query->where('role_id',$params['role_id']);
            }
            if ($params['nickname']){
                $query->where('nickname','like','%'.$params['nickname'].'%');
            }
        })
            ->with('address')
            ->orderBy('id','DESC')
            ->paginate(15);
        return $this->returnJson(0,'获取用户列表成功',$info);
    }

    /**
     * 获取用户登录信息
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function info(){
        $id = auth()->guard('api')->id();
        $info = User::find($id);
        return $this->returnJson(0,'',$info);
    }

    /**
     * 更新用户信息
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function update(){
        $id = (int)request('id','');
        $data['nickname'] = (string)request('username','');
        $data['password'] = bcrypt(request('password',''));
        try{
            if($id>0){
                $find = User::find($id);
                if($find){
                    $find->update($data);
                }
            }else{
                $data['openid'] = $data['nickname'];
               User::create($data);
            }

            return $this->returnJson(0,'');
        }catch (\Exception $e){
            Log::error($e->getMessage());
            return $this->returnJson(1,'操作失败');
        }
    }

    /**
     * 删除用户
     * @return \Illuminate\Http\JsonResponse
     * Author: DaXiong
     */
    public function destroy(){
        $id = (int)request('id','');
        if($id){
            try{
                User::destroy($id);
                return $this->returnJson(0,'');
            }catch (\Exception $e){
                Log::error($e->getMessage());
                return $this->returnJson(1,'操作失败');
            }
        }
    }
}